import CryptoJS from 'crypto-js'

// AES加密，key为Base64编码的密钥，返回Base64编码的密文
export function aesEncrypt(plaintext, keyBase64) {
  // 将Base64密钥转为WordArray
  const key = CryptoJS.enc.Base64.parse(keyBase64)
  // 生成随机IV
  const iv = CryptoJS.lib.WordArray.random(16)
  // 加密（使用CBC模式和PKCS#7填充）
  const encrypted = CryptoJS.AES.encrypt(plaintext, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  // 拼接IV和密文并转为Base64
  const ciphertext = iv.concat(encrypted.ciphertext)
  const ciphertextBase64 = ciphertext.toString(CryptoJS.enc.Base64)
  return ciphertextBase64
}

// AES解密，key为Base64编码的密钥，返回明文
export function aesDecrypt(ciphertextBase64, keyBase64) {
  // Base64解码
  const ciphertext = CryptoJS.enc.Base64.parse(ciphertextBase64)
  // 提取IV和密文
  const iv = CryptoJS.lib.WordArray.create(ciphertext.words.slice(0, 4)) // 16字节IV
  const encrypted = CryptoJS.lib.WordArray.create(ciphertext.words.slice(4))
  // 将Base64密钥转为WordArray
  const key = CryptoJS.enc.Base64.parse(keyBase64)
  // 解密
  const decrypted = CryptoJS.AES.decrypt({ ciphertext: encrypted }, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  const plaintext = decrypted.toString(CryptoJS.enc.Utf8)
  return plaintext
}
